<?php

namespace app\common\model;

use addons\xykeep\exception\Exception;
use app\api\model\xykeep\User;
use app\common\model\Teacher as TeacherModel;
use app\common\model\TeacherOrder as TeacherOrderModel;
use think\Config;
use think\Model;


class DepositOrder extends Model
{

    

    

    // 表名
    protected $name = 'deposit_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'paytime_text',
        'platform_text',
        'status_text'
    ];
    

    
    public function getPayTypeList()
    {
        return ['wechat' => __('Wechat'), 'balance' => __('Balance')];
    }

    public function getPlatformList()
    {
        return ['wxMiniProgram' => __('Platform wxminiprogram'), 'wxOfficialAccount' => __('Platform wxofficialaccount')];
    }

    public function getStatusList()
    {
        return ['-3' => __('Status -3') ,'-1' => __('Status -1'), '0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPlatformTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['platform']) ? $data['platform'] : '');
        $list = $this->getPlatformList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 添加订单
     */
    public static function addOrder($params){

        extract($params);

        $TeacherOrderModel = new TeacherOrderModel();
        $order_info = $TeacherOrderModel->where('id',$teacher_order_id)->find();

        if (!$order_info) {
            new Exception('订单不存在！');
        }

        if($pay_service=='deposit'){
            $total_money = Config::get('site.deposit_money');
        }else if($pay_service=='agency'){
            $total_money = Config::get('site.agency_money');
        }else{
            new Exception('支付类型错误！');
        }


        $user = User::info();

        $close_time = 15;//15分钟为支付自动关闭
        $orderData = [];
        $orderData['order_sn'] = createOrderNo();
        $orderData['user_id'] = $user->id;
        $orderData['total_amount'] = $total_money;
        $orderData['total_fee'] = $total_money;
        $orderData['service_type'] = $pay_service;
        $orderData['ext'] = json_encode([
            'expired_time' => time() + ($close_time * 60),
        ]);
        $orderData['teacher_order_id'] = $teacher_order_id;

        $order = self::create($orderData);


        return $order;
    }


    /*
     * 订单支付成功
     * */
    public function paySuccess($order, $notify)
    {
        $order->status = 1;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = $notify['payment_json'];
        $order->pay_type = $notify['pay_type'];
        $order->pay_fee = $notify['pay_fee'];
        $order->save();


        $TeacherOrderModel = new TeacherOrderModel();
        $teacherOrder = $TeacherOrderModel->where([
            'id' => $order['teacher_order_id'],
        ])->find();

        $nbnormal_order = TeacherOrderModel::where([
            'teacher_id'=>$order['user_id'],
            'abnormal' => ['neq','']
        ])->find();

        if($order['service_type']=='deposit'){//费用类型
            $teacherOrder->pay_deposit = 1;
        }else{//
            $teacherOrder->pay_agency = 1;
        }

        if($nbnormal_order){//需要同时支付押金和中介费
            if($teacherOrder->pay_deposit && $teacherOrder->pay_agency){
                $teacherOrder->status = 2;
            }
        }else{
            if($teacherOrder->pay_agency){
                $teacherOrder->status = 2;
            }
        }

        $teacherOrder->save();


        //每次接单获得半颗星
        $params['star'] = 0.5;
        $params['user_id'] = $order['user_id'];
        $params['type'] = '接单';
        \think\Hook::listen('teacher_star_change', $params);
    }
}
